package 剑指II;

import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-12-28
 **/

public class Jz035最小时间差 {

    /**
     * 给定一个 24 小时制（小时:分钟 "HH:MM"）的时间列表，找出列表中任意两个时间的最小时间差并以分钟数表示。
     * <p>
     * 示例 1：
     * 输入：timePoints = ["23:59","00:00"]
     * 输出：1
     * 示例 2：
     * 输入：timePoints = ["00:00","23:59","00:00"]
     * 输出：0
     * <p>
     * 提示：
     * 2 <= timePoints <= 2 * 104
     * timePoints[i] 格式为 "HH:MM"
     */

    public int findMinDifference(List<String> timePoints) {

        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();

        for (String timePoint : timePoints) {
            int hour = Integer.parseInt(timePoint.substring(0, 2));
            int min = Integer.parseInt(timePoint.substring(3, 5));
            priorityQueue.add(hour * 60 + min);
        }

        int result = Integer.MAX_VALUE;
        int lastTime = priorityQueue.poll();
        int firstTime = lastTime;

        while (!priorityQueue.isEmpty()) {
            Integer time = priorityQueue.poll();
            result = Math.min(result, this.minTime(lastTime, time));
            lastTime = time;
        }

        result = Math.min(result, this.minTime(firstTime, lastTime));

        return result;
    }

    private int minTime(int time1, int time2) {
        return Math.min(time2 - time1, time1 - time2 + 1440);
    }

    public static void main(String[] args) {
        Jz035最小时间差 n = new Jz035最小时间差();
        int result = n.findMinDifference(Arrays.asList("00:37", "23:59", "02:09"));
        System.out.println(result);
    }

}
